<template>
  <div class="level-container">
    <div class="level-header">
      <button class="back-btn" @click="goBack">← 返回</button>
      <h2 class="level-title">{{ levelData.name }}</h2>
      <div class="progress">{{ currentQuestion + 1 }} / {{ questions.length }}</div>
    </div>

    <div class="level-content">
      <div class="question-area">
        <h3 class="question-text">找到相同的形状</h3>

        <div class="target-shape">
          <div class="shape" :class="`shape--${currentQuestionData.target}`"></div>
        </div>

        <div class="options-grid">
          <DraggableItem
            v-for="(option, index) in currentQuestionData.options"
            :key="`shape-${index}`"
            :item-id="`shape-${option}`"
            :item-value="option"
            item-type="shape"
          >
            <div class="shape-card">
              <div class="shape" :class="`shape--${option}`"></div>
            </div>
          </DraggableItem>
        </div>
      </div>

      <div class="answer-area">
        <DropZone
          ref="dropZoneRef"
          zone-id="answer"
          :accepted-value="currentQuestionData.target"
          accepted-type="shape"
          :show-result="true"
          @drop="handleDrop"
        >
          <template #placeholder>
            <div class="drop-placeholder">
              <span class="drop-hint">把相同的形状拖到这里</span>
            </div>
          </template>
          <template #content="{ value }">
            <div class="shape" :class="`shape--${value}`"></div>
          </template>
        </DropZone>
      </div>
    </div>

    <!-- 完成弹窗 -->
    <div v-if="showComplete" class="modal-overlay">
      <div class="modal-content complete-modal">
        <h2>🎉 太棒了！</h2>
        <div class="stars-earned">
          <span v-for="i in starsEarned" :key="i" class="star-big">⭐</span>
        </div>
        <p class="complete-message">你获得了 {{ starsEarned }} 颗星星！</p>
        <div class="complete-buttons">
          <button class="btn btn-primary" @click="goToMap">返回地图</button>
          <button v-if="hasNextLevel" class="btn btn-secondary" @click="goToNextLevel">
            下一关
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useGameStore } from '@/stores/game'
import DraggableItem from '@/components/common/DraggableItem.vue'
import DropZone from '@/components/common/DropZone.vue'
import { soundManager } from '@/utils/sound'
import { createStarEffect, createCelebrationEffect, injectAnimationStyles } from '@/utils/animation'

const router = useRouter()
const route = useRoute()
const gameStore = useGameStore()

const levelId = parseInt(route.params.id as string)
const levelData = computed(() => gameStore.levels.find(l => l.id === levelId)!)

const currentQuestion = ref(0)
const correctAnswers = ref(0)
const showComplete = ref(false)
const dropZoneRef = ref<InstanceType<typeof DropZone>>()

// 形状类型
const shapes = ['circle', 'square', 'triangle', 'star', 'heart']

// 题目数据
const questions = ref([
  { target: 'circle', options: ['circle', 'square', 'triangle', 'star'] },
  { target: 'square', options: ['square', 'circle', 'heart', 'triangle'] },
  { target: 'triangle', options: ['triangle', 'square', 'circle', 'star'] },
  { target: 'star', options: ['star', 'heart', 'square', 'triangle'] },
  { target: 'heart', options: ['heart', 'circle', 'star', 'square'] }
])

const currentQuestionData = computed(() => questions.value[currentQuestion.value])

const starsEarned = computed(() => {
  const accuracy = correctAnswers.value / questions.value.length
  if (accuracy >= 0.9) return 3
  if (accuracy >= 0.7) return 2
  return 1
})

const hasNextLevel = computed(() => {
  const nextLevel = gameStore.levels.find(l => l.id === levelId + 1)
  return nextLevel !== undefined
})

onMounted(() => {
  injectAnimationStyles()
  // 打乱选项
  questions.value.forEach(q => {
    q.options = shuffleArray(q.options)
  })
})

function shuffleArray<T>(array: T[]): T[] {
  const newArray = [...array]
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[newArray[i], newArray[j]] = [newArray[j], newArray[i]]
  }
  return newArray
}

function handleDrop(data: { correct: boolean }) {
  if (data.correct) {
    correctAnswers.value++

    const dropZone = dropZoneRef.value?.$el
    if (dropZone) {
      const rect = dropZone.getBoundingClientRect()
      createStarEffect(rect.left + rect.width / 2, rect.top + rect.height / 2)
    }

    setTimeout(() => {
      if (currentQuestion.value < questions.value.length - 1) {
        currentQuestion.value++
        dropZoneRef.value?.reset()
      } else {
        completeLevel()
      }
    }, 1500)
  } else {
    setTimeout(() => {
      dropZoneRef.value?.reset()
    }, 1000)
  }
}

function completeLevel() {
  showComplete.value = true
  gameStore.completeLevel(levelId, starsEarned.value)
  createCelebrationEffect()
  soundManager.playBadge()
}

function goBack() {
  router.push('/')
}

function goToMap() {
  router.push('/')
}

function goToNextLevel() {
  router.push(`/level/${levelId + 1}`)
  currentQuestion.value = 0
  correctAnswers.value = 0
  showComplete.value = false
}
</script>

<style scoped>
.level-container {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 30px 20px;
  box-sizing: border-box;
  margin: 0;
}

.level-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  padding: 0 20px;
}

.back-btn {
  font-size: 24px;
  padding: 12px 24px;
  background: #fff;
  border: 2px solid #9C27B0;
  border-radius: 15px;
  cursor: pointer;
  font-weight: bold;
  color: #9C27B0;
  transition: all 0.2s;
}

.back-btn:hover {
  background: #9C27B0;
  color: #fff;
}

.level-title {
  font-size: 36px;
  color: #7B1FA2;
  margin: 0;
}

.progress {
  font-size: 24px;
  font-weight: bold;
  color: #7B1FA2;
  background: #fff;
  padding: 10px 20px;
  border-radius: 15px;
}

.level-content {
  max-width: 1200px;
  margin: 0 auto;
}

.question-area {
  background: #fff;
  border-radius: 20px;
  padding: 40px;
  margin-bottom: 40px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.question-text {
  font-size: 48px;
  text-align: center;
  color: #333;
  margin: 0 0 40px 0;
}

.target-shape {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 30px;
  justify-items: center;
}

.shape-card {
  width: 150px;
  height: 150px;
  background: #fff;
  border: 4px solid #9C27B0;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6px 16px rgba(156, 39, 176, 0.3);
}

.shape {
  width: 80px;
  height: 80px;
}

.shape--circle {
  background: #FF5722;
  border-radius: 50%;
}

.shape--square {
  background: #2196F3;
  border-radius: 8px;
}

.shape--triangle {
  width: 0;
  height: 0;
  background: transparent;
  border-left: 40px solid transparent;
  border-right: 40px solid transparent;
  border-bottom: 80px solid #4CAF50;
}

.shape--star {
  background: #FFC107;
  clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
}

.shape--heart {
  background: #E91E63;
  position: relative;
  transform: rotate(-45deg);
  border-radius: 50% 50% 0 0;
}

.shape--heart::before,
.shape--heart::after {
  content: '';
  position: absolute;
  width: 80px;
  height: 80px;
  background: #E91E63;
  border-radius: 50%;
}

.shape--heart::before {
  top: -40px;
  left: 0;
}

.shape--heart::after {
  left: 40px;
  top: 0;
}

.answer-area {
  display: flex;
  justify-content: center;
}

.drop-placeholder {
  padding: 40px;
}

.drop-hint {
  font-size: 24px;
  color: #999;
}

/* 完成弹窗样式与之前相同 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.complete-modal {
  background: #fff;
  border-radius: 30px;
  padding: 60px;
  text-align: center;
  animation: scaleIn 0.5s;
}

@keyframes scaleIn {
  from {
    transform: scale(0.5);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

.complete-modal h2 {
  font-size: 48px;
  margin: 0 0 30px 0;
  color: #4CAF50;
}

.stars-earned {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
}

.star-big {
  font-size: 64px;
  animation: starPop 0.5s ease-out;
}

@keyframes starPop {
  0% {
    transform: scale(0) rotate(0deg);
  }
  50% {
    transform: scale(1.2) rotate(180deg);
  }
  100% {
    transform: scale(1) rotate(360deg);
  }
}

.complete-message {
  font-size: 28px;
  color: #333;
  margin-bottom: 40px;
}

.complete-buttons {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.btn {
  padding: 15px 40px;
  font-size: 24px;
  border: none;
  border-radius: 15px;
  cursor: pointer;
  font-weight: bold;
  transition: transform 0.2s;
}

.btn:hover {
  transform: scale(1.05);
}

.btn-primary {
  background: #4CAF50;
  color: #fff;
}

.btn-secondary {
  background: #FF9800;
  color: #fff;
}
</style>
